package com.pengli.mytools.ui.mainPage;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.FeatureGroupInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.jaeger.library.StatusBarUtil;
import com.pengli.mytools.MyApplication;
import com.pengli.mytools.R;
import com.pengli.mytools.listeners.DownloadApkListener;
import com.pengli.mytools.retrofit.NetConstant;
import com.pengli.mytools.ui.mainPage.classification.ClassificationFragment;
import com.pengli.mytools.ui.mainPage.collection.CollectionFragment;
import com.pengli.mytools.ui.mainPage.home.HomeFragment;
import com.pengli.mytools.ui.mainPage.mine.MineFragment;
import com.pengli.mytools.views.dialog.MyPopDialog;
import com.pgyer.pgyersdk.PgyerSDKManager;
import com.pgyer.pgyersdk.callback.CheckoutCallBack;
import com.pgyer.pgyersdk.model.CheckSoftModel;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "下载进度";
    @BindView(R.id.nav_view)
    BottomNavigationView bottomNavigationView;

//    @BindView(R.id.progress_horizontal)
//    ProgressBar progress_horizontal;

    private List<Fragment> mFragments = new ArrayList<>();
    private Context context;
    private String appName = "mytools.apk";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        context = this;

        StatusBarUtil.setTransparent(this);
        StatusBarUtil.setTranslucent(this,80);

        ButterKnife.bind(this);
        MyApplication.getInstance().addActivity(this);

        initBottomNavigation();
        initFragmentData();

        checkUpdate();

        showStatement();
    }

    private void showStatement() {
        SharedPreferences pre = MyApplication.getInstance().getPre();
        if (!pre.getBoolean("showflag", false)) {
            MyPopDialog myPopDialog = new MyPopDialog(context, R.layout.dialog_statement);
            myPopDialog.show();
            pre.edit().putBoolean("showflag", true).commit();
        }
    }

    private void checkUpdate() {
        try {
            PgyerSDKManager.checkVersionUpdate(MainActivity.this, new CheckoutCallBack() {
                @Override
                public void onNewVersionExist(CheckSoftModel model) {
                    //检查版本成功（有新版本）

                    /**
                     *   CheckSoftModel 参数介绍
                     *
                     *    private int buildBuildVersion;//蒲公英生成的用于区分历史版本的build号
                     *     private String forceUpdateVersion;//强制更新版本号（未设置强置更新默认为空）
                     *     private String forceUpdateVersionNo;//强制更新的版本编号
                     *     private boolean needForceUpdate;//	是否强制更新
                     *     private boolean buildHaveNewVersion;//是否有新版本
                     *     private String downloadURL;//应用安装地址
                     *     private String buildVersionNo;//上传包的版本编号，默认为1 (即编译的版本号，一般来说，编译一次会
                     *    变动一次这个版本号, 在 Android 上叫 Version Code。对于 iOS 来说，是字符串类型；对于 Android 来
                     *    说是一个整数。例如：1001，28等。)
                     *     private String buildVersion;//版本号, 默认为1.0 (是应用向用户宣传时候用到的标识，例如：1.1、8.2.1等。)
                     *     private String buildShortcutUrl;//	应用短链接
                     *     private String buildUpdateDescription;//	应用更新说明
                     */
//                    "https://www.pgyer.com/app/installUpdate/c23aafa9c5790c8f4d39da9bb4d93b41?sig=r8oZLD5t%2BoBCUYqLwjj1hyV7no%2BMLKk1%2FGvjSjZpY58oH6hpt39NTsdyLt9xwKZ8&forceHttps="
                    String downloadURL = model.getDownloadURL();
                    int length = NetConstant.fileDownloadBaseUrl.length();
                    String substring = downloadURL.substring(length, downloadURL.length());

                    Call<ResponseBody> responseBodyCall = MyApplication.getInstance().getFileService().downloadFileUrl(substring);
                    responseBodyCall.enqueue(new Callback<ResponseBody>() {
                        @Override
                        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                            if (response.isSuccessful()) {
                                boolean writtenToDisk = writeFileToSDCard(response.body(), appName, downloadListener);
                                if (writtenToDisk) {
                                    Log.d(TAG, "下载成功");
                                }
                            } else {
                                Log.d(TAG, "下载失败");
                            }
                        }

                        @Override
                        public void onFailure(Call<ResponseBody> call, Throwable t) {

                        }
                    });
//
                }

                @Override
                public void onNonentityVersionExist(String string) {
                    //无新版本
                    Toast.makeText(context, string, Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onFail(String error) {
                    //请求异常
                }
            });
        } catch (Exception e) {
            //手动上报异常
            PgyerSDKManager.reportException(e);
        }
    }


    private boolean writeFileToSDCard(ResponseBody body, String fileName, DownloadApkListener downloadApkListener) {
        try {
            // todo change the file location/name according to your needs
            downloadApkListener.onStart();
            String apkPath = getExternalCacheDir().getPath() + File.separator + "app" + File.separator;
            File file = new File(apkPath);
            file.mkdir();
            File futureStudioIconFile = new File(apkPath, fileName);
            InputStream inputStream = null;
            OutputStream outputStream = null;
            try {
                byte[] fileReader = new byte[4096];
                long fileSize = body.contentLength();
                long fileSizeDownloaded = 0;
                inputStream = body.byteStream();
                outputStream = new FileOutputStream(futureStudioIconFile);
                while (true) {
                    int read = inputStream.read(fileReader);
                    if (read == -1) {
                        break;
                    }
                    outputStream.write(fileReader, 0, read);
                    fileSizeDownloaded += read;
                    Log.d(TAG, "file download: " + fileSizeDownloaded/fileSize);
                    //计算当前下载百分比，并经由回调传出
                    downloadApkListener.onProgress((int) (100 * fileSizeDownloaded / fileSize));
                    //当百分比为100时下载结束，调用结束回调，并传出下载后的本地路径
                    if ((int) (100 * fileSizeDownloaded / fileSize) == 100) {
                        downloadApkListener.onFinish(); //下载完成
                    }
                }
                outputStream.flush();
                return true;
            } catch (IOException e) {
                downloadApkListener.onError(e.getMessage());
                return false;
            } finally {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            }
        } catch (IOException e) {
            downloadApkListener.onError(e.getMessage());
            return false;
        }
    }


    public DownloadApkListener downloadListener = new DownloadApkListener() {
        @Override
        public void onStart() {

        }

        @Override
        public void onProgress(int p) {
//            progress_horizontal.setVisibility(View.VISIBLE);
//            progress_horizontal.setProgress(p);
        }

        @Override
        public void onFinish() {
//            progress_horizontal.setVisibility(View.GONE);
            //调用，apkPath 入参就是 xml 中共享的路径
            String apkPath = context.getExternalCacheDir().getPath() + File.separator + "app" + File.separator;
            installApk(context, apkPath);

        }

        @Override
        public void onError(String msg) {

        }
    };


    /**
     * 安装apk
     */
    public void installApk(Context context, String apkPath) {
        if (TextUtils.isEmpty(apkPath)) {
            Toast.makeText(context, "更新失败！未找到安装包", Toast.LENGTH_SHORT).show();
            return;
        }

        File apkFile = new File(apkPath
                + appName);

        Intent intent = new Intent(Intent.ACTION_VIEW);
        //Android 7.0 系统共享文件需要通过 FileProvider 添加临时权限，否则系统会抛出 FileUriExposedException .
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(context, "com.pengli.mytools", apkFile);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setDataAndType(
                    Uri.fromFile(apkFile),
                    "application/vnd.android.package-archive");
        }
        context.startActivity(intent);
    }


    private void initFragmentData() {
        mFragments.add(new HomeFragment());
        mFragments.add(new ClassificationFragment());
        mFragments.add(new CollectionFragment());
        mFragments.add(new MineFragment());
        // 初始化展示MessageFragment
        setFragmentPosition(0);
    }

    private void initBottomNavigation() {
        bottomNavigationView.setOnNavigationItemSelectedListener(
                menuItem -> {
                    menuItem.setChecked(true);
                    switch (menuItem.getItemId()) {
                        case R.id.navigation_home:
                            setFragmentPosition(0);
                            break;
                        case R.id.navigation_classification:
                            setFragmentPosition(1);
                            break;
                        case R.id.navigation_collection:
                            setFragmentPosition(2);
                            break;
                        case R.id.navigation_mine:
                            setFragmentPosition(3);
                            break;
                    }
                    return false;
                });
    }

    private void setFragmentPosition(int position) {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        Fragment fragment = mFragments.get(position);
        ft.replace(R.id.nav_host_fragment, fragment);
        ft.show(fragment);
        ft.commitAllowingStateLoss();
    }

}
